<template>
    <view class="chat-page page-content">
        <!-- 消息列表 -->
        <scroll-view class="w-common chat-page-messages page-content-body" scroll-y :scroll-top="scrollTop" scroll-with-animation>
            <view v-if="messages.length > 0">
                <view v-for="(message, index) in messages" :key="message.id" class="message-item" :class="message.isMe ? 'message-me' : 'message-other'">
                    <!-- 头像 -->
                    <view class="message-avatar">
                        <image :src="message.avatar" mode="aspectFill" />
                    </view>

                    <!-- 消息内容 -->
                    <view class="message-content" :class="`message-${message.type}`">
                        <!-- 文本消息 -->
                        <text v-if="message.type === 'text'">{{ message.content }}</text>

                        <!-- 图片消息 -->
                        <image v-else-if="message.type === 'image'" :src="message.content" mode="aspectFill" @click="previewImage(message.content)" />
                    </view>
                </view>
            </view>

            <!-- 空状态 -->
            <view class="chat-empty" v-else-if="!loading">
                <image class="chat-empty-icon" src="/static/chat/user_avatar.png" mode="aspectFit" />
                <text class="chat-empty-text">暂无消息</text>
            </view>

            <!-- 加载状态 -->
            <view class="chat-loading" v-if="loading">
                <text class="chat-loading-text">加载中...</text>
            </view>
        </scroll-view>

        <!-- 输入框 -->
        <view class="chat-page-input">
            <input class="input-field" v-model="inputText" placeholder="请输入消息..." @confirm="handleConfirm" :disabled="sending" />
            <view class="send-btn" :class="{disabled: !inputText.trim() || sending}" @click="handleSendClick"> 发送 </view>
        </view>
    </view>
</template>

<script setup>
import {ref, onMounted, nextTick, watch} from 'vue';
import {getChatMessages, sendMessage as sendMessageApi} from '@/mock/index.js';
import {useSocket} from '@/hooks/useSocket';
const {send} = useSocket({
    url: 'ws://localhost:18565/ws',
    onMessage: (message) => {
        console.log(message);
    },
});

// 获取页面参数
const chatId = ref(null);

// 响应式数据
const messages = ref([]);
const loading = ref(false);
const inputText = ref('');
const sending = ref(false);
const scrollTop = ref(0);

// 获取聊天消息
const fetchMessages = async () => {
    if (!chatId.value) return;

    try {
        loading.value = true;
        const response = await getChatMessages(chatId.value);
        if (response.code === 200) {
            messages.value = response.data;

            // 滚动到底部
            nextTick(() => {
                scrollToBottom();
            });
        }
    } catch (error) {
        console.error('获取消息失败:', error);
        uni.showToast({
            title: '获取消息失败',
            icon: 'none',
        });
    } finally {
        loading.value = false;
    }
};

// 发送消息的核心逻辑
const sendMessage = async () => {
    if (!inputText.value.trim() || sending.value) return;

    const content = inputText.value.trim();
    inputText.value = '';

    try {
        sending.value = true;
        const response = await sendMessageApi(chatId.value, {
            type: 'text',
            content: content,
        });

        if (response.code === 200) {
            // messages.value.push(response.data);
            // console.log(messages.value);
            // 滚动到底部
            nextTick(() => {
                scrollToBottom();
            });
        }
    } catch (error) {
        console.error('发送消息失败:', error);
        uni.showToast({
            title: '发送失败',
            icon: 'none',
        });
    } finally {
        sending.value = false;
    }
};

// 处理输入框确认事件（回车键）
const handleConfirm = () => {
    sendMessage();
};

// 处理发送按钮点击事件
const handleSendClick = () => {
    send({
        type: 'text',
        content: inputText.value.trim(),
    });
    sendMessage();
};

// 滚动到底部
const scrollToBottom = () => {
    const query = uni.createSelectorQuery();
    query.select('.chat-page-messages').boundingClientRect();
    query.exec((res) => {
        if (res[0]) {
            scrollTop.value = res[0].height;
        }
    });
};

// 预览图片
const previewImage = (src) => {
    uni.previewImage({
        urls: [src],
        current: src,
    });
};

// 监听消息变化，自动滚动到底部
watch(
    messages,
    () => {
        nextTick(() => {
            scrollToBottom();
        });
    },
    {deep: true}
);

// 页面加载时获取数据
onMounted(() => {
    // connect();
    // 获取页面参数
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    chatId.value = currentPage.options.id;

    if (chatId.value) {
        fetchMessages();
    }
});
</script>

<style lang="scss" scoped>
@import '@/styles/chat.chat.scss';
</style>
